package business;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import orm.CollectivityTeachingPlanWeek;
import orm.CollectivityWeekArrange;
import orm.CollectivityWeekTimeBucket;
import orm.TeachingPlanBaseInfo;
import orm.TopicTransferModel;
import util.DBHelper;
import util.Utility;
import dao.CTeachingPlanWeekDAO;
import dao.CWeekArrangeDAO;
import dao.CWeekTimeBucketDAO;
import dao.TeacherDAO;
import dao.TeachingPlanBaseInfoDAO;

public class CTeachingPlanWeekInfoServlet extends BaseServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * Constructor of the object.
	 */
	public CTeachingPlanWeekInfoServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String strFunc = request.getParameter("func");
		Connection con = null;
		Statement stmt = null;
		if (strFunc.equals("load")) {
			gotoCTPWInfo(request, response);
			request.getRequestDispatcher("../" + Utility.JSP_CTeachingPlanWeekInfo).forward(request, response);
		} else if (strFunc.equals("edit")) {
			String strCWeekArrangeID = request.getParameter("cWeekArrangeID");
			
			CollectivityWeekTimeBucket[] cwtb = null;
			CollectivityWeekArrange[] cwa = null;
			
			CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
			CWeekArrangeDAO cwaDAO = new CWeekArrangeDAO();
			CWeekTimeBucketDAO cwtbDAO = new CWeekTimeBucketDAO();
			TeachingPlanBaseInfoDAO tpbiDAO = new TeachingPlanBaseInfoDAO();
			
			try {
				CollectivityTeachingPlanWeek ctpw = ctpwDAO.getCTPWeekByCWAID(strCWeekArrangeID);
				ArrayList<CollectivityWeekArrange> alCWA = cwaDAO.getCWAByCWAID(strCWeekArrangeID);
				ArrayList<CollectivityWeekTimeBucket> alCWTB = cwtbDAO.getCWTBByCWAID(strCWeekArrangeID);
				ArrayList<TeachingPlanBaseInfo> alMonthThemeName = tpbiDAO.getMonthThemeNameByTPProperty();
				ArrayList<TeachingPlanBaseInfo> alWeekThemeName = tpbiDAO.getWeekThemeNameByTPProperty();
				
				String strThemeActivity = "";
				String strActivityArea = "";
				String strOpenAir = "";
				String strActivitySchedules = "";
				String tpid = null;
				
				cwa = new CollectivityWeekArrange[alCWA.size()];
				for(int k = 0; k < alCWA.size(); k++){
					String activitySchedules = "";
					strActivitySchedules = alCWA.get(k).getActivitySchedules();
					String[] alActivitySchedules = strActivitySchedules.split(",");
					if(alActivitySchedules != null){
						for(int m = 0;m < alActivitySchedules.length; m++){
							tpid = alActivitySchedules[m];
							String temp = tpbiDAO.getThemeActivityNameByTPID(tpid);
							if(temp != null && !temp.equals("")){
								if(!activitySchedules.equals("")){
									activitySchedules+=",";
								}
								activitySchedules += temp;
							}
						}
					}
					cwa[k] = new CollectivityWeekArrange();
					cwa[k].setActivitySchedulesName(activitySchedules);
				}
				
				
//				ArrayList themeActivityName = null;
				cwtb = new CollectivityWeekTimeBucket[alCWTB.size()];
				for(int i = 0; i < alCWTB.size(); i++){
					String themeActivityName = "";
					String activityAreaName = "";
					String openAirName = "";
					
					strThemeActivity = alCWTB.get(i).getThemeActivity();
					strActivityArea = alCWTB.get(i).getActivityArea();
					strOpenAir = alCWTB.get(i).getOpenAir();
					String[] alThemeActivity = strThemeActivity.split(",");
					String[] alActivityArea = strActivityArea.split(",");
					String[] alOpenAir = strOpenAir.split(",");
					if(alThemeActivity != null){
						for(int j = 0; j < alThemeActivity.length; j++){
							tpid = alThemeActivity[j];
							String temp = tpbiDAO.getThemeActivityNameByTPID(tpid);
							if(temp!=null && !temp.equals("")){
								if(!themeActivityName.equals("")){
									themeActivityName+=",";
								}
								themeActivityName += temp;
							}
						}
					}
					cwtb[i] = new CollectivityWeekTimeBucket();
					cwtb[i].setThemeActivityName(themeActivityName);
					
					
					if(alActivityArea != null){
						for(int j = 0; j < alActivityArea.length; j++){
							tpid = alActivityArea[j];
							String temp = tpbiDAO.getThemeActivityNameByTPID(tpid);
							if(temp!=null && !temp.equals("null")){
								if(!activityAreaName.equals("")){
									activityAreaName+=",";
								}
								activityAreaName += temp;
							}
						}
					}
					cwtb[i].setActivityAreaName(activityAreaName);
					if(alOpenAir != null){
						for(int j = 0; j < alOpenAir.length; j++){
							tpid = alOpenAir[j];
							String temp = tpbiDAO.getThemeActivityNameByTPID(tpid);
							if(temp!=null && !temp.equals("")){
								if(!openAirName.equals("")){
									openAirName+=",";
								}
								openAirName += temp;
							}
						}
					}
					cwtb[i].setOpenAirName(openAirName);
				}
				
				request.setAttribute("CTPW", ctpw);
				request.setAttribute("CWAArr", alCWA);
				request.setAttribute("CWTBArr", alCWTB);
				request.setAttribute("CWTBNames", cwtb);
				request.setAttribute("CWANames", cwa);
				request.setAttribute("MonthThemeNameArr", alMonthThemeName);
				request.setAttribute("WeekThemeNameArr", alWeekThemeName);
					
				request.getRequestDispatcher("../" + 
							Utility.JSP_CTPWeekArrangeEdit).forward(request, response);
				
			} catch (SQLException e) {
				e.printStackTrace();
			}
		} else if (strFunc.equals("delete")) {
			String cWeekArrangeID = request.getParameter("cWeekArrangeID");
			String strTPID = request.getParameter("hdTPID");
			try {
				con = DBHelper.getConnection();
				con.setAutoCommit(false);
				stmt = con.createStatement();
				
				CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
				CWeekArrangeDAO cwaDAO = new CWeekArrangeDAO();
				CWeekTimeBucketDAO cwtbDAO = new CWeekTimeBucketDAO();
				
				ctpwDAO.deleteCTPWeek(stmt, cWeekArrangeID);
				cwaDAO.deleteCWeekkArrange(stmt, cWeekArrangeID);
				cwtbDAO.deleteCWeekTimeBucket(stmt, cWeekArrangeID);

				con.commit();
				stmt.close();
				
				gotoCTPWInfo(request, response);
				request.getRequestDispatcher("../" + Utility.JSP_CTeachingPlanWeekInfo).forward(request, response);
				
				con.close();
			} catch (SQLException e) {
				e.printStackTrace();
				try {
					con.rollback();
				} catch (SQLException ee) {
					ee.printStackTrace();
				}
			} 
		} else if (strFunc.equals("paging")) {
			com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
			
			Integer teacherID = teacher.getTeacherId();
			int PageSize = Utility.PageSize;
			String strSub = request.getParameter("sub");
			String tmp = request.getParameter("HDPageNo");
			int nPageNo = Integer.parseInt(tmp); 
			String monthThemeName = null;
			String weekThemeName = null;
			String executionDate = null;
			
			if(request.getParameter("MonthThemeName") != null && !request.getParameter("MonthThemeName").equals("")){
				monthThemeName = request.getParameter("MonthThemeName");
			}
			if(request.getParameter("WeekThemeName") != null && !request.getParameter("WeekThemeName").equals("")){
				weekThemeName = request.getParameter("WeekThemeName");
				
			}
			if(request.getParameter("ExecutionDate") != null && !request.getParameter("ExecutionDate").equals("")){
				executionDate = request.getParameter("ExecutionDate");
				
			}
			
			CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
			CollectivityTeachingPlanWeek ctpw = null;
			
			try {
				ArrayList al = ctpwDAO.getSearchCondition(monthThemeName, weekThemeName, executionDate, teacherID);
				int totalPage = 0;
				if (al.size() % PageSize == 0) {
					totalPage = al.size()/PageSize;
					request.setAttribute("totalPage",totalPage);
				} else {
					totalPage = (al.size()/PageSize) + 1;
					request.setAttribute("totalPage",totalPage);
				}
				
				if (strSub == null)
				{
					
				} else if (strSub.equals("start")) {
					nPageNo = 1;
				} else if (strSub.equals("front")) {
					nPageNo--;
				} else if (strSub.equals("next")) {
					nPageNo++;
				} else if (strSub.equals("last")) {
					nPageNo = totalPage ;
				} 
				request.setAttribute("pageNo", nPageNo);
				al = new ArrayList<CollectivityTeachingPlanWeek>();
				ListIterator<CollectivityTeachingPlanWeek> it = ctpwDAO.getSearchCondition(monthThemeName, weekThemeName, executionDate, teacherID).listIterator();
				int ii = 0;
				while (it.hasNext()) {
					ii++;
					CollectivityTeachingPlanWeek t = it.next();
					if (ii <= PageSize * (nPageNo - 1))
						continue;
					
					ctpw = new CollectivityTeachingPlanWeek();
					ctpw.setCWeekArrangeID(t.getCWeekArrangeID());
					ctpw.setMonthThemeName(t.getMonthThemeName());
					ctpw.setWeekThemeName(t.getWeekThemeName());
					ctpw.setConstitutor(t.getConstitutor());
					ctpw.setClassID(t.getClassID());
					ctpw.setExecutionDate(t.getExecutionDate());
					
					al.add(ctpw);
					
					if(ii > PageSize * nPageNo - 1 ) {
						break;
					}
				}
				request.setAttribute("CTPWList", al);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../" + Utility.JSP_CTeachingPlanWeekInfo).forward(request, response);
			
		} else if (strFunc.equals("searchPage")) {
			com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
			
			Integer teacherID = teacher.getTeacherId();
			int PageSize = Utility.PageSize;
			String strSub = request.getParameter("sub");
			String tmp = request.getParameter("PageNo");
			int nPageNo = Integer.parseInt(tmp);
			String monthThemeName = null;
			String weekThemeName = null;
			String executionDate = null;
			
			if(request.getParameter("MonthThemeName") != null && !request.getParameter("MonthThemeName").equals("")){
				monthThemeName = request.getParameter("MonthThemeName");
			}
			if(request.getParameter("WeekThemeName") != null && !request.getParameter("WeekThemeName").equals("")){
				weekThemeName = request.getParameter("WeekThemeName");
				
			}
			if(request.getParameter("ExecutionDate") != null && !request.getParameter("ExecutionDate").equals("")){
				executionDate = request.getParameter("ExecutionDate");
				
			}

			CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
			try {
				ArrayList al = ctpwDAO.getSearchCondition(monthThemeName, weekThemeName, executionDate, teacherID);
				int totalPage = 0;
				if (al.size() % PageSize == 0) {
					request.setAttribute("totalPage",al.size()/PageSize);
				} else {
					request.setAttribute("totalPage",(al.size()/PageSize) + 1);
				}
				
				request.setAttribute("pageNo", nPageNo);
				al = new ArrayList<CollectivityTeachingPlanWeek>();
				ListIterator<CollectivityTeachingPlanWeek> it = ctpwDAO.getSearchCondition(monthThemeName, weekThemeName, executionDate, teacherID).listIterator();
				int ii = 0;
				while (it.hasNext()) {
					ii++;
					CollectivityTeachingPlanWeek t = it.next();
					if (ii <= PageSize * (nPageNo - 1))
						continue;
					
					CollectivityTeachingPlanWeek ctpw = new CollectivityTeachingPlanWeek();
					ctpw.setCWeekArrangeID(t.getCWeekArrangeID());
					ctpw.setMonthThemeName(t.getMonthThemeName());
					ctpw.setWeekThemeName(t.getWeekThemeName());
					ctpw.setConstitutor(t.getConstitutor());
					ctpw.setClassID(t.getClassID());
					ctpw.setExecutionDate(t.getExecutionDate());
					
					al.add(ctpw);
					
					if(ii > PageSize * nPageNo - 1 ) {
						break;
					}
				}
				
				request.setAttribute("CTPWList", al);	
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../" + Utility.JSP_CTeachingPlanWeekInfo).forward(request, response);
		} else if (strFunc.equals("showNetwork")) {
			String strCWeekArrangeID = request.getParameter("cWeekArrangeID");
			CWeekArrangeDAO cwaDAO = new CWeekArrangeDAO();
			CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
			try {
				List<TopicTransferModel> models = cwaDAO.queryTopicModels(cwaDAO.getTPIDSSByCWeekArrangeID(strCWeekArrangeID));
				Map<Integer,List<String>> developmentDomainActivityMapping = new HashMap<Integer,List<String>>();
				for(TopicTransferModel t : models){
					List<String> temp = developmentDomainActivityMapping.get(t.getDevelopmentDomain());
					if(temp==null){
						developmentDomainActivityMapping.put(t.getDevelopmentDomain(), temp=new ArrayList<String>());
					}
					temp.add(t.getActiveName());
				}
				
				CollectivityTeachingPlanWeek ctpw = ctpwDAO.getCTPWNetByCWAID(strCWeekArrangeID);
				
				request.setAttribute("developmentDomainActivityMapping", developmentDomainActivityMapping);
				request.setAttribute("CTPWArr", ctpw);
				request.setAttribute("cWeekArrangeID", strCWeekArrangeID);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../" + Utility.JSP_CTPWeekNetwork).forward(request, response);
		} else if (strFunc.equals("SearchCondition")) {
			com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
			
			Integer teacherID = teacher.getTeacherId();
			CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
			CollectivityTeachingPlanWeek ctpw = null;
			
			String monthThemeName = null;
			String weekThemeName = null;
			String executionDate = null;
			
			if(request.getParameter("MonthThemeName") != null && !request.getParameter("MonthThemeName").equals("")){
				monthThemeName = request.getParameter("MonthThemeName");
			}
			if(request.getParameter("WeekThemeName") != null && !request.getParameter("WeekThemeName").equals("")){
				weekThemeName = request.getParameter("WeekThemeName");
				
			}
			if(request.getParameter("ExecutionDate") != null && !request.getParameter("ExecutionDate").equals("")){
				executionDate = request.getParameter("ExecutionDate");
				
			}
		
			try {
				request.setAttribute("pageNo", 1);
				int PageSize = Utility.PageSize;
				ArrayList al = ctpwDAO.getSearchCondition(monthThemeName, weekThemeName, executionDate, teacherID);
				int totalPage = 0;
				if (al.size() % PageSize == 0) {
					totalPage = al.size()/PageSize;
					request.setAttribute("totalPage",totalPage);
				} else {
					totalPage = (al.size()/PageSize) + 1;
					request.setAttribute("totalPage",totalPage);
				}
		
				al = new ArrayList<CollectivityTeachingPlanWeek>();
				ListIterator<CollectivityTeachingPlanWeek> it = ctpwDAO.getSearchCondition(monthThemeName, weekThemeName, executionDate, teacherID).listIterator();
				int ii = 0;
				while (it.hasNext()) {
					CollectivityTeachingPlanWeek t = it.next();
					
					ctpw = new CollectivityTeachingPlanWeek();
					ctpw.setCWeekArrangeID(t.getCWeekArrangeID());
					ctpw.setMonthThemeName(t.getMonthThemeName());
					ctpw.setWeekThemeName(t.getWeekThemeName());
					ctpw.setConstitutor(t.getConstitutor());
					ctpw.setClassID(t.getClassID());
					ctpw.setExecutionDate(t.getExecutionDate());
					
					al.add(ctpw);
					ii++;
		
					if(ii > (PageSize-1)) {
						break;
					}
				}
				request.setAttribute("CTPWList", al);	
			} catch (SQLException e) {
				e.printStackTrace();
			}	
			request.getRequestDispatcher("../" + Utility.JSP_CTeachingPlanWeekInfo).forward(request, response);
		} else if (strFunc.equals("CTPWNetworkMore")) {
			String strCWeekArrangeID = request.getParameter("CWeekArrangeID");
			int intActivityOptionSize = Integer.parseInt(request.getParameter("ActivityOptionSize"));
			String strActivityOptionName = request.getParameter("ActivityOptionName");
			strActivityOptionName = new String(strActivityOptionName.getBytes("iso-8859-1"),"utf-8"); 
			CWeekArrangeDAO cwaDAO = new CWeekArrangeDAO();
			CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
			try {
				List<TopicTransferModel> models = cwaDAO.queryTopicModels(cwaDAO.getTPIDSSByCWeekArrangeID(strCWeekArrangeID));
				Map<Integer,List<String>> developmentDomainActivityMapping = new HashMap<Integer,List<String>>();
				for(TopicTransferModel t : models){
					List<String> temp = developmentDomainActivityMapping.get(t.getDevelopmentDomain());
					if(temp==null){
						developmentDomainActivityMapping.put(t.getDevelopmentDomain(), temp=new ArrayList<String>());
					}
					temp.add(t.getActiveName());
				}
				
				CollectivityTeachingPlanWeek ctpw = ctpwDAO.getCTPWNetByCWAID(strCWeekArrangeID);
				
				request.setAttribute("developmentDomainActivityMapping", developmentDomainActivityMapping);
				request.setAttribute("CTPWArr", ctpw);
				request.setAttribute("cWeekArrangeID", strCWeekArrangeID);
				request.setAttribute("ActivityOptionSize", intActivityOptionSize);
				request.setAttribute("ActivityOptionName", strActivityOptionName);
			} catch (SQLException e) {
				e.printStackTrace();
			}
			request.getRequestDispatcher("../" + Utility.JSP_CTPWNetworkMore).forward(request, response);
		} 
		
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

	public void gotoCTPWInfo(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException{
			CTeachingPlanWeekDAO ctpwDAO = new CTeachingPlanWeekDAO();
			CollectivityTeachingPlanWeek ctpw = null;
			
			com.zmht.specedu.vo.Teacher teacher = this.getCurrentUser(request); 
			
			Integer teacherID = teacher.getTeacherId();
		
			try {
				request.setAttribute("pageNo", 1);
				int PageSize = Utility.PageSize;
				ArrayList al = ctpwDAO.getAllCTeachingPlanWeek(teacherID);
				int totalPage = 0;
				if (al.size() % PageSize == 0) {
					totalPage = al.size()/PageSize;
					request.setAttribute("totalPage",totalPage);
				} else {
					totalPage = (al.size()/PageSize) + 1;
					request.setAttribute("totalPage",totalPage);
				}
		
				al = new ArrayList<CollectivityTeachingPlanWeek>();
				ListIterator<CollectivityTeachingPlanWeek> it = ctpwDAO.getAllCTeachingPlanWeek(teacherID).listIterator();
				int ii = 0;
				while (it.hasNext()) {
					CollectivityTeachingPlanWeek t = it.next();
					
					ctpw = new CollectivityTeachingPlanWeek();
					ctpw.setCWeekArrangeID(t.getCWeekArrangeID());
					ctpw.setMonthThemeName(t.getMonthThemeName());
					ctpw.setWeekThemeName(t.getWeekThemeName());
					ctpw.setConstitutor(t.getConstitutor());
					ctpw.setClassID(t.getClassID());
					ctpw.setExecutionDate(t.getExecutionDate());
					
					al.add(ctpw);
					ii++;
		
					if(ii > (PageSize-1)) {
						break;
					}
				}
				request.setAttribute("CTPWList", al);	
			} catch (SQLException e) {
				e.printStackTrace();
			}	
		}
	
	}
